package com.aysafety.eventmodel.service.hydraulicSupport.impl;

import com.aysafety.eventmodel.common.DateUtils;
import com.aysafety.eventmodel.dao.HydraulicSupportDao;
import com.aysafety.eventmodel.dao.MicroseismDao;
import com.aysafety.eventmodel.dao.TreeDao;
import com.aysafety.eventmodel.service.hydraulicSupport.HydraulicSupportService;
import com.safety.algorithm.eigenvalue.EigenvalueAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;

/**
 * @program: iotDataPlatform
 * @description: 液压支架
 * @author: ChengQi
 * @create: 2019-02-20 20:01
 **/
@Service public class HydraulicSupportServiceImpl implements HydraulicSupportService {

    @Autowired TreeDao treeDao;

    @Autowired HydraulicSupportDao hydraulicsupportDao;
    @Autowired
    MicroseismDao microseismDao;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 删除ArrayList中重复元素，保持顺序
    private static List<Map<String, Object>> removeDuplicateWithOrder(List<Map<String, Object>> list) {
        Set<Map<String, Object>> set = new HashSet<Map<String, Object>>();
        List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>(2);
            map.put("entId", list.get(i).get("entId"));
            map.put("deviceId", list.get(i).get("deviceId"));
            if (set.add(map)) {
                newList.add(map);
            }
        }
        return newList;
    }


    @Override public void countFrequency(String currentTime) throws Exception {

        //[t-1min,t]
        String startTime =
            DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeMinuteDate(-10, currentTime));
        String endTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", currentTime);

        Map<String, Object> treeMap = new HashMap<String, Object>(1);
        treeMap.put("type", "\'" + "hydraulicSupport" + "\'");
        List<Map<String, Object>> tree = removeDuplicateWithOrder(treeDao.queryTreeData(treeMap));
        for (Map<String, Object> treeData : tree) {
            String mineId = treeData.get("entId").toString();
            String deviceId = treeData.get("deviceId").toString();
            //查询实时数据
            Map<String, Object> parram = new HashMap<String, Object>();
            parram.put("tableId", mineId + "." + "HydraulicSupportRealTime");
            parram.put("entId", "\'" + mineId + "\'");
            parram.put("deviceId", "\'" + deviceId + "\'");
            parram.put("startTime", DateUtils.fomatDateTime(startTime).getTime());
            parram.put("endTime", DateUtils.fomatDateTime(endTime).getTime());
            //查询半小时内所有数据
            List<Map<String, Object>> datas = hydraulicsupportDao.queryRealTimeByHydraulicSupport(parram);
            for (int i = 0; i < datas.size(); i++) {
                int leftFrequency = 0;
                int rightFrequency = 0;
                int totalFrequency = 0;
                Map<String, Object> map = datas.get(i);
                //查询[dataTime-6,dataTime]数据
                long eTime = (long) map.get("datetime");
                long sTime = eTime - 6 * 60 * 60 * 1000;
                parram.put("startTime", sTime);
                parram.put("endTime", eTime);
                List<Map<String, Object>> subDatas = hydraulicsupportDao.queryRealTimeByHydraulicSupport(parram);
                for (Map<String, Object> data : subDatas) {
                    if (data.containsKey("leftPressure") && Double.valueOf(data.get("leftPressure").toString()) > 0.0) {
                        leftFrequency++;
                    }
                    if (data.containsKey("rightPressure")
                        && Double.valueOf(data.get("rightPressure").toString()) > 0.0) {
                        rightFrequency++;
                    }
                    if (data.containsKey("totalStrain") && Double.valueOf(data.get("totalStrain").toString()) > 0.0) {
                        totalFrequency++;
                    }
                }
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("pk", "\'" + eTime + ".:." + deviceId + "\'");
                resultMap.put("entId", "\'" + mineId + "\'");
                resultMap.put("deviceId", "\'" + deviceId + "\'");
                resultMap.put("datetime", eTime);
                resultMap.put("leftFrequency", leftFrequency);
                resultMap.put("rightFrequency", rightFrequency);
                resultMap.put("totalFrequency", totalFrequency);
                resultMap.put("tableId", mineId + "." + "CalHyFrequency");
                hydraulicsupportDao.saveFrequency(resultMap);
            }
        }
    }

    @Override public void countFlicker(String currentTime) throws Exception {
        //[t-30min,t]
        String startTime =
            DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeMinuteDate(-10, currentTime));
        String endTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", currentTime);

        Map<String, Object> treeMap = new HashMap<String, Object>(1);
        treeMap.put("type", "\'" + "hydraulicSupport" + "\'");
        List<Map<String, Object>> tree = removeDuplicateWithOrder(treeDao.queryTreeData(treeMap));
        for (Map<String, Object> treeData : tree) {
            String mineId = treeData.get("entId").toString();
            String deviceId = treeData.get("deviceId").toString();
            //查询b半个小时内实时数据
            Map<String, Object> parram = new HashMap<String, Object>();
            parram.put("tableId", mineId + "." + "HydraulicSupportRealTime");
            parram.put("entId", "\'" + mineId + "\'");
            parram.put("deviceId", "\'" + deviceId + "\'");
            parram.put("startTime", DateUtils.fomatDateTime(startTime).getTime());
            parram.put("endTime", DateUtils.fomatDateTime(endTime).getTime());

            List<Map<String, Object>> realList = hydraulicsupportDao.queryRealTimeByHydraulicSupport(parram);
            for (int i = 0; i < realList.size(); i++) {
                /***********************1.取出2天的数据***********************/
                Map<String, Object> map = realList.get(i);
                //查询[dataTime-6,dataTime]数据
                long eTime = (long) map.get("datetime");
                long sTime = eTime - 24 * 60 * 60 * 1000;
                parram.put("startTime", sTime);
                parram.put("endTime", eTime);
                List<Map<String, Object>> datas = hydraulicsupportDao.queryRealTimeByHydraulicSupport(parram);
                /***********************1.计算平均值***********************/
                int leftFrequency = 0;
                int rightFrequency = 0;
                int totalFrequency = 0;
                double sumLeft = 0.0;//左柱压力总和
                double sumRight = 0.0;//右柱压力总和
                double sumTotal = 0.0;//整柱压力总和
                double avgLeft = 0.0;//左柱压力均值
                double avgRight = 0.0;//右柱压力均值
                double avgTotal = 0.0;//整柱压力均值

                //计算和值
                for (Map<String, Object> data : datas) {
                    if (data.containsKey("leftPressure") && Double.valueOf(data.get("leftPressure").toString()) > 0.0) {
                        leftFrequency++;
                        sumLeft += Double.valueOf(data.get("leftPressure").toString());
                    }
                    if (data.containsKey("rightPressure")
                        && Double.valueOf(data.get("rightPressure").toString()) > 0.0) {
                        rightFrequency++;
                        sumRight += Double.valueOf(data.get("rightPressure").toString());
                    }
                }

                sumTotal = sumLeft + sumRight;
                totalFrequency = leftFrequency + rightFrequency;

                //计算均值
                if (datas.size() > 0) {
                    avgLeft = sumLeft / leftFrequency;
                    avgRight = sumRight / rightFrequency;
                    avgTotal = sumTotal / totalFrequency;
                    /***********************3.判断波动***********************/
                    double percentAvgLeft = avgLeft / 10;
                    double percentAvgRight = avgRight / 10;
                    double percentAvgTotal = avgTotal / 10;
                    for (Map<String, Object> data : datas) {
                        Map<String, Object> resultMap = new HashMap<String, Object>();
                        resultMap.put("pk", "\'" + eTime + ".:." + deviceId + "\'");
                        resultMap.put("entId", "\'" + mineId + "\'");
                        resultMap.put("deviceId", "\'" + deviceId + "\'");
                        resultMap.put("datetime", eTime);
                        resultMap.put("tableId", mineId + "." + "CalHyFlicker");

                        double leftPressure = Double.parseDouble(data.get("leftPressure").toString());//左
                        double rightPressure = Double.parseDouble(data.get("rightPressure").toString());//右
                        double totalStrain = leftPressure + rightPressure;//整
                        if (leftPressure > avgLeft) {
                            resultMap.put("leftFlag", 2);
                        } else if (leftPressure > percentAvgLeft && leftPressure <= avgLeft) {
                            resultMap.put("leftFlag", 1);
                        } else {
                            resultMap.put("leftFlag", 0);
                        }

                        if (rightPressure > avgRight) {
                            resultMap.put("rightFlag", 2);
                        } else if (rightPressure > percentAvgRight && rightPressure <= avgRight) {
                            resultMap.put("rightFlag", 1);
                        } else {
                            resultMap.put("rightFlag", 0);
                        }
                        if (totalStrain > avgTotal) {
                            resultMap.put("totalFlag", 2);
                        } else if (totalStrain > percentAvgTotal && totalStrain <= avgTotal) {
                            resultMap.put("totalFlag", 1);
                        } else {
                            resultMap.put("totalFlag", 0);
                        }
                        hydraulicsupportDao.saveFlicker(resultMap);
                    }
                }
            }

        }
    }

    @Override
    public void flickerIntervalRiskRealTime(String currentTime) throws Exception {
        //[t-160min,t] 计算当前时间前60分钟内
        //String startTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeMinuteDate(-160, currentTime));
        String startTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeDayDate(-2, currentTime, "yyyy-MM-dd HH:mm:ss"));
        String endTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", currentTime);


        Map<String, Object> treeMap = new HashMap<String, Object>(1);
        treeMap.put("type", "\'" + "hydraulicSupport" + "\'");
        List<Map<String, Object>> tree = removeDuplicateWithOrder(treeDao.queryTreeData(treeMap));
        for (Map<String, Object> treeData : tree) {

            String mineId = treeData.get("entId").toString();
            String deviceId = treeData.get("deviceId").toString();

            // 拼接查询需要的参数
            Map<String, Object> params = new HashMap<>();
            params.put("tableId", mineId + "." + "CALHYFLICKER");
            params.put("startTime", DateUtils.fomatDateTime(startTime).getTime());
            params.put("endTime", DateUtils.fomatDateTime(endTime).getTime());
            params.put("deviceId", "\'" + deviceId + "\'");

            List<Map<String, Object>> flickerResults = hydraulicsupportDao.queryFlickerInterval(params);

            if (null != flickerResults || !flickerResults.isEmpty()) {
                handleFlickerIntervalStr0(mineId, deviceId, flickerResults);
            }
        }
    }


    @Override
    public Map<String, Map<String, Long>> flickerIntervalRisk(Map<String, Map<String, Long>> lastStrMap, String currentTime) throws Exception {
        // Map<lastStr, datetime>
        //Map<String, Long> lastStrAndDatetime = new HashMap<>();
        Map<String, Map<String, Long>> map  = new HashMap<>();
        //[t-60min,t] 计算当前时间前60分钟内
        String startTime =
                DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeMinuteDate(-60, currentTime));
        String endTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", currentTime);

        Map<String, Object> treeMap = new HashMap<String, Object>(1);
        treeMap.put("type", "\'" + "hydraulicSupport" + "\'");
        List<Map<String, Object>> tree = removeDuplicateWithOrder(treeDao.queryTreeData(treeMap));
        for (Map<String, Object> treeData : tree) {

            String mineId = treeData.get("entId").toString();
            //String mineId = "hujiahe";
            String deviceId = treeData.get("deviceId").toString();

            // 拼接查询需要的参数
            Map<String, Object> params = new HashMap<>();
            params.put("tableId", mineId + "." + "CALHYFLICKER");
            params.put("startTime", DateUtils.fomatDateTime(startTime).getTime());
            params.put("endTime", DateUtils.fomatDateTime(endTime).getTime());
            params.put("deviceId", "\'" + deviceId + "\'");

            List<Map<String, Object>> flickerResults = hydraulicsupportDao.queryFlickerInterval(params);

            Map<String, Long> lastStrAndDatetime = lastStrMap.get(deviceId);
            /**
             * lastStrMap:结构
             * [
             *  deviceID1:{
             *              str1:datetime1
             *  },
             * deviceID2:{
             *              str2:datetime2
             *  },
             * ]
             * */
            if (null != flickerResults || !flickerResults.isEmpty()) {
                String flickerIntervalStr = listToString(flickerResults, "leftflag");
                if (null == lastStrAndDatetime) {
                    Map<String, Long> temp = handleFlickerIntervalStr0(mineId, deviceId, flickerResults);
                    map.put(deviceId, temp);
                } else {
                    for (Map.Entry<String, Long> entry : lastStrAndDatetime.entrySet()) {
                        flickerIntervalStr = entry.getKey() + flickerIntervalStr;
                        logger.info("上一个lastStr: " + entry.getKey());
                        Map<String, Long> temp = handleFlickerIntervalStr(mineId, deviceId, flickerIntervalStr, flickerResults, lastStrMap);
                        map.put(deviceId,temp);
                    }
                }
            }
        }
        return map;
    }


    /**
     * 处理一段时间的闪烁值
     * @param mineId
     * @param deviceId
     * @param flickerIntervalStr
     * @param flickerResults
     * @param lastStrMap
     * @return
     */
    protected Map<String, Long> handleFlickerIntervalStr(String mineId, String deviceId,
                                                         String flickerIntervalStr,
                                                         List<Map<String, Object>> flickerResults,
                                                         Map<String, Map<String, Long>> lastStrMap) {

        Map<String, Long> lastStrAndDatetime = lastStrMap.get(deviceId);
        Map<String, Long> map = new HashMap<>();
        List<Long> list = new ArrayList<>(3);
        Collection<Long> datetimes = lastStrAndDatetime.values();
        for (Long datetime : datetimes) {
            list.add(0, datetime);
        }
        String flickerStr = listToString(flickerResults, "leftflag");
        char[] charArray = flickerStr.toCharArray();
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == '2') {
                if (list.size() == 0 || list.size() == 1) {
                    list.clear();

                    list.add(0, (long) flickerResults.get(i).get("DATETIME"));
                } else if (list.size() == 2 ) {
                    list.add(2, (long) flickerResults.get(i).get("DATETIME"));
                    /*
                     * 此时已经找到了202,直接入库
                     */
                    long t1 = list.get(0);
                    long t2 = list.get(2);
                    double I = computeI(t1, t2);
                    logger.info("  t1: " + t1 + "  t2: " + t2 + "  I: " + I);
                    Map<String, Object> row = flickerIntervalRiskRow(mineId, deviceId, flickerResults.get(i), I, t2);
                    hydraulicsupportDao.insertFlickerIntervalRisk(row);
                    // 临时数组清空
                    list.clear();
                    list.add(0, (long) flickerResults.get(i).get("DATETIME"));
                }
            }
            if (charArray[i] == '0') {
                if (list.size() == 1) {
                    list.add(1, 0L);
                }

            }
        }
        if (flickerStr.contains("2")) {
            int last2Index = flickerStr.lastIndexOf("2");
            logger.info("lastStr: " + flickerStr.substring(last2Index));
            map.put(flickerStr.substring(last2Index), (long) flickerResults.get(last2Index).get("DATETIME"));
        } else {

            int last2Index = flickerIntervalStr.lastIndexOf("2");
            String lastStr = flickerIntervalStr.substring(last2Index);
            Collection<Long> datetimes1 = lastStrAndDatetime.values();
            for (Long datetime : datetimes1) {
                map.put(lastStr, datetime);
            }
        }
        return map;
    }

    /**
     * 处理一段时间的闪烁值
     * @param flickerResults
     * @return
     */
    private Map<String, Long> handleFlickerIntervalStr0(String mineId, String deviceId, List<Map<String, Object>> flickerResults) {

        Map<String, Long> lastStrAndDatetime = new HashMap<>();
        List<Long> list = new ArrayList<>(3);
        String flickerIntervalStr = listToString(flickerResults, "leftflag");
        if (flickerIntervalStr.contains("2")) {
            char[] charArray = flickerIntervalStr.toCharArray();
            for (int i = 0; i < charArray.length; i++) {
                if (charArray[i] == '2') {
                    if (list.size() == 0 || list.size() == 1) {
                        list.clear();
                        list.add(0, (long) flickerResults.get(i).get("DATETIME"));
                    } else if (list.size() == 2 ) {
                        list.add(2, (long) flickerResults.get(i).get("DATETIME"));
                        /*
                         * 此时已经找到了202,直接入库
                         */
                        long t1 = list.get(0);
                        long t2 = list.get(2);
                        double I = computeI(t1, t2);
                        logger.info("  t1: " + t1 + "  t2: " + t2 + "  I: " + I);
                        Map<String, Object> row = flickerIntervalRiskRow(mineId, deviceId, flickerResults.get(i), I, t2);
                        hydraulicsupportDao.insertFlickerIntervalRisk(row);
                        // 临时数组清空
                        list.clear();
                        list.add(0, (long) flickerResults.get(i).get("DATETIME"));
                    }
                }
                if (charArray[i] == '0') {
                    if (list.size() == 1) {
                        list.add(1, 0L);
                    }
                }
            }
            int last2Index = flickerIntervalStr.lastIndexOf("2");
            String lastStr = flickerIntervalStr.substring(last2Index);
            logger.info("lastStr: " + flickerIntervalStr.substring(last2Index));
            lastStrAndDatetime.put(lastStr, (long) flickerResults.get(last2Index).get("DATETIME"));
        } else {
            lastStrAndDatetime = null;
        }
        return lastStrAndDatetime;
    }


    /**
     * 计算闪烁间隔危险度,并返回
     */
    protected Map<String, Object> flickerIntervalRiskRow(String mineId, String deviceId, Map<String, Object> map,
                                                         double I1, long secondDatetime) {
        Map<String, Object> row = new HashMap<>();
        row.put("tableId", mineId + "." + "FlickerIntervalRisk");
        row.put("pk", "\'" + map.get("pk") + "\'");
        row.put("entId", "\'" + map.get("entId") + "\'");
        row.put("deviceId", "\'" + deviceId + "\'");
        row.put("datetime", secondDatetime);
        row.put("I", I1);
        return row;
    }

    /**
     * 计算闪烁危险度
     */
    private double computeI(long firstDatetime, long secondDatetime) {
        double I;
        long firstDatetime1 = firstDatetime / 1000;
        long secondDatetime1 = secondDatetime / 1000;
        BigDecimal hourDatetime1 = new BigDecimal(firstDatetime1);
        BigDecimal hourDatetime2 = new BigDecimal(secondDatetime1);
        BigDecimal t1 = hourDatetime1.divide(BigDecimal.valueOf(3600), 6, BigDecimal.ROUND_UP);
        BigDecimal t2 = hourDatetime2.divide(BigDecimal.valueOf(3600), 6, BigDecimal.ROUND_UP);
        if (t1.equals(t2)) {
            I = 0.0;
        } else {
            BigDecimal temp1 = t2.subtract(t1).setScale(6,BigDecimal.ROUND_UP);
            System.out.println(temp1.doubleValue());
            BigDecimal temp2 = new BigDecimal(1.0).divide(temp1, 6, BigDecimal.ROUND_UP);
            I = temp2.setScale(4,BigDecimal.ROUND_UP).doubleValue();
        }
        System.out.println(I);
        logger.info("闪烁间隔危险度为： " + I);
        return I;
    }

    private String listToString(List<Map<String, Object>> flickerResults, String label) {
        String flickerIntervalStr = "";
        for (Map<String, Object> map : flickerResults) {
            Double leftFlag = (Double) map.get(label);
            flickerIntervalStr = flickerIntervalStr + String.valueOf(leftFlag).substring(0, 1);
        }
        return flickerIntervalStr;
    }

    /*public static void main(String[] args) {
        double I;
        BigDecimal hourDatetime1 = new BigDecimal(1552970370);
        BigDecimal hourDatetime2 = new BigDecimal(1552970773);
        BigDecimal t1 = hourDatetime1.divide(BigDecimal.valueOf(3600), 6, BigDecimal.ROUND_UP);
        BigDecimal t2 = hourDatetime2.divide(BigDecimal.valueOf(3600), 6, BigDecimal.ROUND_UP);
        if (t1.equals(t2)) {
            I = 0.0;
        } else {
            BigDecimal temp1 = t2.subtract(t1).setScale(6,BigDecimal.ROUND_UP);
            System.out.println(temp1.doubleValue());
            BigDecimal temp2 = new BigDecimal(1.0).divide(temp1, 6, BigDecimal.ROUND_UP);
            I = temp2.setScale(4,BigDecimal.ROUND_UP).doubleValue();
        }
        System.out.println(I);
    }*/

    /**
     * 计算实时综合预警的w
     * @param currentTime
     * @return
     * @throws Exception
     */
    @Override
    public void warning(String currentTime) throws Exception {
        //[t-1min,t]
        String startTime =
                DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", DateUtils.getBeforeMinuteDate(-60, currentTime));
        String endTime = DateUtils.getCurrentMinuteStartTime("yyyy-MM-dd HH:mm:ss", currentTime);

        Map<String, Object> treeMap = new HashMap<String, Object>(1);
        treeMap.put("type", "\'" + "hydraulicSupport" + "\'");

        long etime = 0l;
        // 树
        List<Map<String, Object>> tree = removeDuplicateWithOrder(treeDao.queryTreeData(treeMap));
        for (Map<String, Object> treeData : tree) {
            String entId = treeData.get("entId").toString();
            long sTime = DateUtils.fomatDateTime(startTime).getTime();
            long eTime = DateUtils.fomatDateTime(endTime).getTime();
            Map<String, Object> parram = new HashMap<String, Object>();
            parram.put("tableId", entId + "." + "MICROSEISMREALTIME");
            parram.put("startTime", "\'" + sTime + "\'");
            parram.put("endTime", "\'" + eTime + "\'");
            List<Map<String, Object>> datas = microseismDao.queryRealMicroseism(parram);

            if (0 == datas.size()) {
                continue;
            }

            int maxw = 0;
            //double maxw2 = 0;
            double sumR = 0.0;
            Map<Double, Double> rw = new HashMap<>();
            Map<String, Map<Double, Double>> warnResult = new HashMap<>();
            //查询学习出来的临界值
            parram.put("tableId", "HYDRAULICSUPPORTWARNINGSTUDY");
            parram.put("pk", "\'" + entId + "\'");
            List<Map<String, Object>> studyInfos = hydraulicsupportDao.queryHydraulicSupportStudy(parram);
            for (Map<String, Object> studyInfo : studyInfos) {
                double best1 = Double.parseDouble(studyInfo.get("best1").toString());
                double best2 = Double.parseDouble(studyInfo.get("best2").toString());
                double best3 = Double.parseDouble(studyInfo.get("best3").toString());
                double R1 = Double.parseDouble(studyInfo.get("R1").toString());
                String deviceId = (String) studyInfo.get("deviceId");
                sumR = sumR + R1;


                for (int i = 0; i < datas.size(); i++) {
                    //查询前8小时数据，判断maxW
                    double emergoa = Double.parseDouble(datas.get(i).get("emergoa").toString());
                    etime = (long) datas.get(i).get("datetime");
                    //long etime = new BigInteger("1549273425000").longValue();
                    long stime = etime;
                    parram.put("endTime", etime);
                    parram.put("startTime", stime);
                    int w3 = 0;

                    // 频次
                    parram.put("tableId", entId + "." + "CALHYFREQUENCY");
                    List<Double> cList3 = hydraulicsupportDao.queryHydraulicSupportFrequency(parram);
                    // 闪烁危险度
                    parram.put("tableId", entId + "." + "FLICKERINTERVALRISK");
                    List<Double> cList4 = hydraulicsupportDao.queryHydraulicSupportFlickerIntervalRisk(parram);
                    if (cList3.size() != 1 || cList4.size() != 1) {
                        //实时能量未计算
                        continue;
                    } else {
                        if (emergoa > best1) {
                            w3++;
                        }
                        if (cList3.get(0) > best2) {
                            w3++;
                        }
                        if (cList4.get(0) > best3) {
                            w3++;
                        }
                        //rw.put(R1, (double) w3);
                    }

                    etime = (long) datas.get(i).get("datetime");
                    stime = etime - 8 * 60 * 60 * 1000;
                    parram.put("endTime", "\'" + etime + "\'");
                    parram.put("startTime", "\'" + stime + "\'");
                    // 实时能量
                    parram.put("tableId", entId + "." + "MICROSEISMREALTIME");
                    List<Map<String, Object>> realList = microseismDao.queryRealMicroseism(parram);
                    List<Double> eList = new LinkedList<Double>();
                    for (int j = 0; j < realList.size(); j++) {
                        eList.add(Double.parseDouble(realList.get(j).get("emergoa").toString()));
                    }

                    parram.put("endTime", etime);
                    parram.put("startTime", stime);
                    // 频次
                    parram.put("tableId", entId + "." + "CALHYFREQUENCY");
                    parram.put("flag",1);
                    List<Double> cList1 = hydraulicsupportDao.queryHydraulicSupportFrequency(parram);
                    // 闪烁危险度
                    parram.put("tableId", entId + "." + "FLICKERINTERVALRISK");
                    List<Double> cList2 = hydraulicsupportDao.queryHydraulicSupportFlickerIntervalRisk(parram);
                    parram.remove("flag");
                    int w1 = 0;

                    for (int j = 0; j < eList.size(); j++) {
                        if (eList.get(j) > best1) {
                            w1++;
                        }
                        if (cList1.get(0) > best2) {
                            w1++;
                        }
                        if (cList2.get(0) > best3) {
                            w1++;
                        }

                        maxw = maxw > w1 ? maxw : w1;
                        rw.put(R1, (double) w1);
                        w1 = 0;
                    }

                    //计算W综
                    //double wz = computeWZ(maxw, sumR, rw);
                    //maxw2 = maxw2 > wz ? maxw2 : wz;
                    Map<Double, Double> temp = new HashMap<>();
                    temp.put(R1, (double) w1);
                    warnResult.put(deviceId, temp);
                }
            }

            //if (warnResult.size() > 0) {
                /*Map<Double, Double> rw1 = new HashMap<>();
                for (Map<Double, Double> map : warnResult.values()) {
                    for (Map.Entry<Double, Double> entry : map.entrySet()) {
                        rw1.put(entry.getKey(), entry.getValue());
                    }
                }*/
                double wResult = computeWZ(maxw, sumR, rw);
                System.out.println("wz:  " + wResult);
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("tableId", entId + "." + "HydraulicsupportWarning");
                resultMap.put("entId", "\'" + entId + "\'");
                resultMap.put("pk", "\'" + etime + "\'");
                resultMap.put("datetime", etime);
            System.out.println("etime: " + etime);
                resultMap.put("w", wResult);
                hydraulicsupportDao.saveWarning(resultMap);
           // }
        }
    }

    /**
     *  计算液压支架多参量综合预警的W值
     * @param maxw
     * @param sumR
     * @param wr
     * @return
     */
    private double computeWZ(double maxw, double sumR, Map<Double, Double> wr) {
        double result = 0.0;
        BigDecimal bigMaxW = new BigDecimal(maxw);
        BigDecimal bigSumR = new BigDecimal(sumR);
        for (Map.Entry<Double, Double> entry : wr.entrySet()) {
            if (maxw == 0.0) {
                result = 0.0;
            } else {
                Double w = entry.getValue();
                BigDecimal bigW = new BigDecimal(w);
                double r = entry.getKey();
                BigDecimal bigR = new BigDecimal(r);

                BigDecimal tempW = bigW.divide(bigMaxW, 2, BigDecimal.ROUND_UP);
                BigDecimal tempR = bigR.divide(bigSumR, 2, BigDecimal.ROUND_UP);
                BigDecimal multiply = tempW.multiply(tempR);
                result = result + multiply.doubleValue();
            }
        }
        return result;
    }

}
